package com.sim.view;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sim.util.LogHelper;
import com.sim.util.ThreadUtil;
import com.sim.web.HelloServer;
import com.sim.web.OkHttpRequest;

public class MainActivity extends Activity {

    private EditText regionText;
    private EditText simText;

    private Button switchSim;
    private Button checkSim;

    private TextView showText;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        regionText = findViewById(R.id.regionText);
        simText = findViewById(R.id.simText);

        switchSim = findViewById(R.id.switchSim);
        checkSim = findViewById(R.id.checkSim);

        showText = findViewById(R.id.showText);

        switchSim.setOnClickListener(view -> new Thread(() -> {
            int regionIndex = Integer.valueOf(regionText.getText().toString());
            int simIndex = Integer.valueOf(simText.getText().toString());
            // TODO http请求
            String httpRequest = "http://127.0.0.1:10086/SimTool?regionIndex=%s&simIndex=%s";

            try {
                ThreadUtil.sleep(1000);
                String result = OkHttpRequest.getResponseString(String.format(httpRequest, regionIndex, simIndex));
                LogHelper.log("http result : " + result);
            } catch (Exception e) {
                LogHelper.log(e);
            }

        }).start());

        checkSim.setOnClickListener(view -> new Thread(() -> {
            try {
                String httpRequest = "http://127.0.0.1:10086/Check";
                String result = OkHttpRequest.getResponseString(httpRequest);
                LogHelper.log("http result : " + result);
                handler.sendMessage(handler.obtainMessage(1, result));
            } catch (Exception e) {
                LogHelper.log(e);
            }
        }).start());
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            showText.setText(msg.obj.toString());
        }
    };
}
